<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>gif播放控制</title>
</head>
<body>
<img src="https://bbsfiles.vivo.com.cn/vivobbs/attachment/forum/201512/14/125320u1uhs1q1l771jv7s.gif" alt="跨域动图" title="跨域动图"/>
<img src="./2.gif" alt="同域动图" title="同域动图"/>
<img src="./3.png" alt="静态图片" title="静态图片"/>
<script type="text/javascript">
    if ('getContext' in document.createElement('canvas')) {
        HTMLImageElement.prototype.play = function() {
            if (this.storeCanvas) {
                // 移除存储的canvas
                this.storeCanvas.parentElement.removeChild(this.storeCanvas);
                this.storeCanvas = null;
            }
            if (this.storeStyle) {
                // 恢复样式
                this.style = this.storeStyle;
                this.storeStyle = null;
            }
            if (this.storeUrl) {
                // 恢复链接
                this.src = this.storeUrl;
                this.storeUrl = null;
            }
        };
        HTMLImageElement.prototype.stop = function() {
            if (!this.src || this.src.lastIndexOf('.gif') !== this.src.length - 4) {
                return;
            }
            var canvas = document.createElement('canvas');
            // 尺寸
            var width = this.width, height = this.height;
            if (width && height) {
                // 存储之前的地址
                this.storeUrl = this.src;
                // canvas大小
                canvas.width = width;
                canvas.height = height;
                // 绘制图片帧（第一帧）
                canvas.getContext('2d').drawImage(this, 0, 0, width, height);
                // 重置当前图片
                try {
                    this.src = canvas.toDataURL("image/gif");
                } catch(e) {
                    // 跨域
                    // 保存样式
                    canvas.className = this.className;
                    canvas.style = this.storeStyle = this.style;
                    // 保存原图引用
                    canvas.storeImg = this;
                    // 前面插入图片
                    this.parentElement.insertBefore(canvas, this);
                    // 隐藏原图
                    this.style.display = "none";
                    // 存储canvas
                    this.storeCanvas = canvas;
                }
            }
        };
        HTMLImageElement.prototype.toggle = function() {
            if (this.storeUrl) {
                this.play();
            } else {
                this.stop();
            }
        };
    }
    document.addEventListener("click", function(e) {
        var target = e.target, tagName = target.tagName.toUpperCase();
        if (tagName === "CANVAS" && target.storeImg) {
            target.storeImg.play();
        } else if (tagName === "IMG") {
            target.toggle();
        }
    })
</script>
</body>
</html>